package notify

import (
	"bytes"
	"fmt"
	"strconv"
	"text/template"
	"work_order/models/system"
	"work_order/pkg/logger"
	"work_order/pkg/notify/dingding"
	"work_order/pkg/notify/email"

	"github.com/spf13/viper"
)

/*
  @Author : lanyulei
  @同时发送多种通知方式
*/

type BodyData struct {
	SendTo        interface{} // 接受人
	EmailCcTo     []string    // 抄送人邮箱列表
	Subject       string      // 标题
	Classify      []int       // 通知类型
	Id            int         // 工单ID
	Title         string      // 工单标题
	Creator       string      // 工单创建人
	Priority      int         // 工单优先级
	PriorityValue string      // 工单优先级
	CreatedAt     string      // 工单创建时间
	Content       string      // 通知的内容
	Description   string      // 表格上面的描述信息
	ProcessId     int         // 流程ID
	Domain        string      // 域名地址
}

func (b *BodyData) ParsingTemplate() (err error) {
	// 读取模版数据
	var (
		buf bytes.Buffer
	)

	tmpl, err := template.ParseFiles("./static/template/email.html")
	if err != nil {
		return
	}

	b.Domain = viper.GetString("settings.domain.url")
	err = tmpl.Execute(&buf, b)
	if err != nil {
		return
	}

	b.Content = buf.String()

	return
}

func (b *BodyData) SendNotify() (err error) {
	var (
		emailList []string
		phoneList []string
	)

	switch b.Priority {
	case 1:
		b.PriorityValue = "正常"
	case 2:
		b.PriorityValue = "紧急"
	case 3:
		b.PriorityValue = "非常紧急"
	}

	for _, c := range b.Classify {
		switch c {
		case 1: // 邮件
			users := b.SendTo.(map[string]interface{})["userList"].([]system.SysUser)
			if len(users) > 0 {
				for _, user := range users {
					emailList = append(emailList, user.Email)
					phoneList = append(phoneList, user.Phone)
				}
				err = b.ParsingTemplate()
				if err != nil {
					logger.Errorf("模版内容解析失败，%v", err.Error())
					return
				}
				go email.SendMail(emailList, b.EmailCcTo, b.Subject, b.Content)

				ROBOT_TOKEN := "aa6d2df9b82032bfaa330989f67b841fa628a285092d60900bb514c89f084fcb"
				ROBOT_SECRET := "SEC4029afbad8388f99e2ade0a074f422dc316e4e58b1fab19a8a8ea39f894885f8"
				robot := dingding.NewRobot(ROBOT_TOKEN, ROBOT_SECRET)
				url := b.Domain + "/#/process/handle-ticket?workOrderId=" + strconv.Itoa(b.Id) + "&processId=" + strconv.Itoa(b.ProcessId)
				head := b.Title
				creator := b.Creator
				priority := b.PriorityValue
				createtime := b.CreatedAt

				a := fmt.Sprintf("# **<font size=10   >工单审批通知 [向右] [点击此处跳转](%s)</font>** \n\n", url)
				k := fmt.Sprintf("标题: **<font>%s</font>** \n\n 申请人: **<font>%s</font>** \n\n 优先级: **<font>%s</font>**  \n\n 申请时间: **<font>%s</font>**\n\n", head, creator, priority, createtime)
				title := "工单审批通知"
				text := []string{
					"![screenshot](https://pic.616pic.com/ys_bnew_img/00/56/43/bq13nNIfMd.jpg) ",
					a,
					k,
				}

				go func() {
					if err := robot.SendMarkdownMessage(title, text, phoneList, false); err != nil {
						panic(err)
					}
				}()
			}
		}
	}
	return
}
